extends Node2D
class_name Attack

signal attack_finish

var base_point_list = [] # 单次攻击的基准点，单向，如果是DIRECTION4的类型，设定一个点就会计算四向
var rela_point_list = [] # 相对于基准点的攻击范围矩阵
var rela_point_dmg = [] # 每个rela_point的伤害数值

var is_set: bool
var to_do_coords = []
var to_do_dmgs = []
var to_do_target_camp: Piece.CAMP

var Grids: GridContainer
var attacker: Piece
var attack_anim: PackedScene

var anim_list = []
var anim_count = 0

func _init(object_in):
	attacker = object_in
	Grids = attacker.get_node("/root/Main_Controller/Grids")
	attack_anim = preload ("res://anims/attack/attack_anim.tscn")

# Enemy 使用的计算最优策略的方法
func calculate_max_dmg(_coord_in, _enemy_type): # 参数：释放时所处的位置，计分的受击类型
	print("base Attack calculate max dmg func, should not be used")

# 追加执行attack的func
func do_attack():
	for i in range(len(to_do_coords)):
		# 去除自己的威胁显示
		Grids.get_child(to_do_coords[i][0] * Chessboard.BOARD_SIZE + to_do_coords[i][1]).update_threat( - 1, -1 * to_do_dmgs[i])
		anim_list[i].play("attack")

# 动画播完之后执行实际的攻击
func on_anim_finish():
	anim_count -= 1
	print("left_anim: ", anim_count)
	if anim_count == 0:
		for i in range(len(to_do_coords)):
			var target = Chessboard.board_array[to_do_coords[i][0]][to_do_coords[i][1]]
			if target != null and (target.camp == to_do_target_camp or to_do_target_camp == Piece.CAMP.ALL):
				target.receive_dmg(to_do_dmgs[i])
		is_set = false
		# 清空旧动画对象
		for anim in anim_list:
			anim.queue_free()
		anim_list.clear()
		attack_finish.emit()

# 预存要执行的attack
func set_attack(coords_in, dmg_in, camp_in):
	to_do_coords = coords_in.duplicate(true)
	to_do_dmgs = dmg_in.duplicate(true)
	to_do_target_camp = camp_in
	is_set = true
	for i in range(len(to_do_coords)):
		var target_grid = Grids.get_child(to_do_coords[i][0] * Chessboard.BOARD_SIZE + to_do_coords[i][1])
		# 追加威胁显示
		target_grid.update_threat(1, to_do_dmgs[i])
		# 追加标记待播放的动画
		var new_anim = attack_anim.instantiate()
		new_anim.position = target_grid.global_position
		# 连接信号，动画播完之后要触发接下来的步骤
		new_anim.animation_finished.connect(on_anim_finish)
		anim_list.append(new_anim)
		attacker.add_child(new_anim)
		anim_count += 1
